package com.gopay.checkorder.service.task;


import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Observable;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.manager.BankOrderManager;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.gopay.sms.common.domain.ResponseVO;
/**
 * 对账报警Task
 * 
 * @CheckOrderFailLogTaskImpl.java
 * @author zhengxue
 * @2014-10-30 下午5:56:21 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderFailLogTaskImpl extends Observable implements Task {
    private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");

    @Resource(name = "bankOrderManager")
    protected BankOrderManager bankOrderManager;

    private static final String SWITCH_ON = "on";

    @Resource(name = "smsConfig")
    private Map<String, String> smsConfig;

    @Override
    public void doTask() {
        logger.error("对账短信报警定时任务start ");
        // edit hougn 2017-09-26 增加失败数阈值 start
        //List list = bankOrderManager.getCheckOrderFailLog();
        List list = bankOrderManager.getCheckOrderFailLog(smsConfig.get("failCount"));
        // edit hougn 2017-09-26 增加失败数阈值 end
        logger.error("对账短信报警定时任务count: " + list.size());

        for (int i = 0; i < list.size(); i++) {
            sendSms((String) list.get(i));
            logger.info(list.get(i) + " CheckOrderFailLogTaskImpl 对账短信报警");
        }
    }

    private void sendSms(String bankName) {

       try {
           if (SWITCH_ON.equals(smsConfig.get("switch"))) {
                // 自定义短信内容，不提供验证码校验功能
                RequestVO req = new RequestVO();
                req.setAppId(SMSAppId._90000.value);
                req.setMobile(smsConfig.get("mobile"));// 电话号码(多个以逗号分隔)
                req.setContent(bankName + " 超过" + smsConfig.get("scale") + "% " + smsConfig.get("content") + " IP: "
                        + this.getLocalIp());
                ResponseVO resp = GopaySMSHttpClient.getInstance().createVerificationCode(req);

                if (resp != null) {
                    if ("100".equals(resp.getStatusCode())) {
                        logger.error("银行【" + bankName + "】预警短信发送成功");
                    } else {
                        logger.error("银行【" + bankName + "】预警短信发送失败，原因：" + resp.getMessage());
                    }
                }
            } else {
                logger.error("checkOrder 预警短信发送已关闭，预警信息: 银行" + bankName + " 与银行服务器、前置机、BIS通信发生异常,已有该业务全部订单超过"
                        + smsConfig.get("scale") + "%的数量无法对单");

            }
        } catch (Exception e) {
            logger.error("senSMS error: ", e);
        }

    }

    // 获取IP地址
    public String getLocalIp() throws Exception {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            // System.out.println(netInterface.getName());
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    logger.error("本机的IP = " + ip.toString());
                    return ip.toString();
                }
            }
        }
        return null;
    }

}
